<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/17
 * Time: 9:37
 */

namespace app\index\controller;


use app\index\model\AdminRatio;
use app\index\model\MemberBalanceInfo;
use app\index\model\MemberTeam;
use app\index\model\WxSet;
use think\Controller;
use app\index\model\Order;
use app\index\model\Member;
use think\facade\Cache;

class BaseController extends Controller
{

    protected $url;
    public function initialize(){
        $this->url = 'http://'.$_SERVER['HTTP_HOST'];
//        $access_token = Cache::store('redis')->get('access_token');
//        if (!$access_token){
//            $this->accessToken();
//        }
    }

//    public function test(){
//        Cache::store('redis')->set('access_token',11111111,7150);
//        $access_token = Cache::store('redis')->get('access_token');
//        dump($access_token);
//    }



//    public function accessToken(){
//        $ret = WxSet::get(1);
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$ret['appID']."&secret=".$ret['secret'];
//        $token = $this->curl($url);
//        Cache::store('redis')->set('access_token',$token['access_token'],7150);
//    }



    public function upload($file){
        $info = $file->move( '../public/uploads');
        if ($info) {
            $result = [
                'code'     => 1,
                'msg'      => '上传成功',
                'filename' => '/uploads/' . str_replace('\\', '/', $info->getSaveName())
            ];
            return $result['filename'];
        } else {
            return false;
        }
    }
    //按照经纬度坐标计算距离
    public function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);

    }
    //二维数组排序
    public function arraySort($arr,$shortKey,$short=SORT_DESC,$shortType=SORT_REGULAR){
        foreach ($arr as $key => $data){
            $name[$key] = $data[$shortKey];
        }
        array_multisort($name,$shortType,$short,$arr);
        return $arr;
    }
    //营业时间转换
    public function shopTimeRestore($time){
        $time = explode("-",$time);
        $today = strtotime(date("Y-m-d"),time());
        $time[0] = $time[0] + $today;
        $time[1] = $time[1] + $today;
        $time[0] = date(' H:i:s',$time[0]);
        $time[1] = date(' H:i:s',$time[1]);
        $ret = implode('-',$time);
        return $ret;
    }
    //生成14为订单号
    public function orderNo(){
        $str = $this->randStr();
        $num = $this->randNum();
        return $str.date('ymd',time()).$num;
    }
    //生成指定位数随机数字
    public function randNum($length = 4){
        return rand(intval(pow(10,($length - 1))),intval(pow(10,$length) - 1));
    }
    //生成指定位数随机字符串
    public function randStr($length = 4,$char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"){
        if (!is_int($length) || $length < 0){
            return false;
        }
        $string = '';
        for ($i=$length;$i>0;$i--){
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }
    public function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    public function MakeSign($params,$key){
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);  //参数进行拼接key=value&k=v
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    public function ToUrlParams($params)
    {
        $string = '';
        if (!empty($params)) {
            $array = array();
            foreach ($params as $key => $value) {
                $array[] = $key . '=' . $value;
            }
            $string = implode("&", $array);
        }
        return $string;
    }






    /**
     * 分销处理
     * @param $order_no string 订单号
     *
     **/
    public function distribution($order_no){
        $order = Order::where('order_no',$order_no)->where('return_status',0)->find();
        if (!$order){
            return 2;
        }
        $user = Member::get((int)$order['user_id']);
        $father = Member::get((int)$user['pid']);
        $ratio = AdminRatio::get(1);
        if ($father){
            $money1 = round($order['money'] * ($ratio['ratio_A']/100),2);
            $upData = [
                'user_id'=>$father['id'],
                'sum'=>$money1,
                'order_no'=>$order_no,
                'time'=>time(),
                'status'=>2
            ];
            $ret1 = MemberBalanceInfo::create($upData);
            $grand = Member::get((int)$father['id']);
            $ret2 = Member::update(['balance'=>$grand['balance']+$money1],['id'=>$father['id']]);
            if ($ret1 && $ret2){
                $one = 1;
            }else{
                $one = 2;
            }
        }else{
            return 1;
        }
        $grandfather = Member::get((int)$father['pid']);
        if ($grandfather){
            $money2 = round($order['money'] * ($ratio['ratio_B']/100),2);
            $upData = [
                'user_id'=>$grandfather['id'],
                'sum'=>$money2,
                'order_no'=>$order_no,
                'time'=>time(),
                'status'=>2
            ];
            $ret1 = MemberBalanceInfo::create($upData);
            $grand = Member::get((int)$grandfather['id']);
            $ret2 = Member::update(['balance'=>$grand['balance']+$money2],['id'=>$grandfather['id']]);
            if ($ret1 && $ret2){
                $two = 1;
            }else{
                $two = 2;
            }
        }else{
            $two = 0;
        }
        $team = MemberTeam::where(['user_id'=>$user['id']])->find();
        if ($team){
            $data = [
                'total_sum'=>$team['total_sum'] + $order['money'],
                'order_num'=>$team['order_num']+1,
            ];
            if ($one==1 && $two==1){
                $data['brokerage_A'] = $team['brokerage_A'] + $money1;
                $data['brokerage_B'] = $team['brokerage_B'] + $money2;
            }elseif($one==1 && $two==0){
                $data['brokerage_A'] = $team['brokerage_A'] + $money1;
            }
            $up = MemberTeam::update($data,['user_id'=>$team['user_id']]);
        }else{
            $data = [
                'user_id'=>$user['id'],
                'total_sum'=>$order['money'],
                'order_num'=>1,
            ];
            if ($one==1 && $two==1){
                $data['brokerage_A'] =  $money1;
                $data['brokerage_B'] =  $money2;
            }elseif($one==1 && $two==0){
                $data['brokerage_A'] =  $money1;
            }
            $up = MemberTeam::create($data);
        }
        if ($up){
            Order::update(['return_status'=>1],['id'=>$order['id']]);
            return 1;
        }else{
            return 0;
        }
    }


    public function waiter($table_id,$order_no){
        $table = ShopTable::where('id',$table_id)->find();
        if ($table['waiter_id'] == 0){
            return 1;
        }
        $order = Order::where('order_no',$order_no)->find();
        $ratio = AdminWaiter::get(1);
        if ($ratio['status'] == 1){
            $money = round($order['money'] * ($ratio['value']/100),2);
            $status = '订单';
        }elseif ($ratio['status'] == 2){
            $money = round($order['order_number'] * $ratio['money'],2);
            $status = '人数';
        }
        $data = [
            'user_id'=>$table['waiter_id'],
            'order_no'=>$order['order_no'],
            'total'=>$order['money'],
            'number'=>$order['order_number'],
            'money'=>$money,
            'status'=>$status,
            'create_time'=>time()
        ];
        $ret = MemberWaiter::create($data);
        if (!$ret){
            return 0;
        }
        return 1;
    }




}